//
//  HCPictureView.swift
//  新浪微博
//
//  Created by fanhoucheng on 16/9/28.
//  Copyright © 2016年 fanhoucheng. All rights reserved.
//

import UIKit
import SnapKit

class HCPictureView: UICollectionView {

    override func awakeFromNib() {
        
        self.backgroundColor = UIColor.gray
        
        addSubview(testLabel)
        
        testLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        self.dataSource = self
        
        self.register(HCPictureCell.self, forCellWithReuseIdentifier: "HCPictureCellId")
    }
    
    var picktureInfo: [HCPicUrl]? {
        didSet {
            testLabel.text = "\(picktureInfo?.count ?? 0)张"
            reloadData()
        }
    }
    
    private lazy var testLabel: UILabel = {
        let l = UILabel(title: "100", textColor: UIColor.white, fontSize: 40)
        
        return l
    }()

}

extension HCPictureView:UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picktureInfo?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HCPictureCellId", for: indexPath) as! HCPictureCell
        
        cell.backgroundColor = UIColor.blue
        cell.pictureInfo = picktureInfo?[indexPath.item]
        
        return cell
    }
}

class HCPictureCell: UICollectionViewCell {
    
    var pictureInfo: HCPicUrl? {
        didSet {
            let url = URL(string: pictureInfo?.thumbnail_pic ?? "")
            imageView.sd_setImage(with: url)
        }
    }
    
    //添加一个 iv
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子视图
        self.contentView.addSubview(imageView)
        //设置约束
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView.snp.edges)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
}
